﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NPMonitor.Implementation.Store;
using NPMonitor.DataModel;
using System.Collections.ObjectModel;
using NPMonitor.Interfaces;
using NPMonitor.Web.Code;
using NPMonitor.Implementation;

namespace NPMonitor.Web.UserControls
{
    public partial class JobScheduleList : System.Web.UI.UserControl
    {
        protected int item = 1;
        protected void Page_Load(object sender, EventArgs e)
        {
            ctPager.PageChange += new PagerControl.PageRefresh(DoBindData);
            lblLRTime.InnerText = DateTime.Now.ToFormatString();
            if (MachineName == null)
                MachineName = Request.Params["MachineName"];
        }

        /// <summary>
        /// 翻页页面大小
        /// </summary>
        protected int PageSize
        {
            get { return ctPager.PageSize; }
        }

        /// <summary>
        /// 当前页数
        /// </summary>
        public int CurrentPageIndex
        {
            get { return ctPager.CurrentPageIndex; }
        }

        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void imgRefresh_OnClick(object sender, EventArgs e)
        {
            DoBindData(ctPager.CurrentPageIndex);
        }

        /// <summary>
        /// 机器名称
        /// </summary>
        public string MachineName
        {
            get
            {
                var state = ViewState["ScheduleMachineName"];
                if (state != null)
                {
                    return ViewState["ScheduleMachineName"].ToString();
                }
                return null;
            }
            set
            {
                ViewState["ScheduleMachineName"] = value;
            }
        }

        public bool HiddenTitle
        {
            set
            {
                phTitle.Visible = value;
            }
        }

        /// <summary>
        /// 绑定列表数据
        /// </summary>
        /// <param name="pageIndex"></param>
        public void DoBindData(int pageIndex)
        {
            int itemCount = 0;
            ReadOnlyCollection<JobData> jobList = StoreManager.Current.JobStore.GetJobsByMachineName(MachineName, pageIndex, PageSize, out itemCount);
            ctPager.IntialProperties(itemCount);
            pageIndex = ctPager.CurrentPageIndex;
            JobListRepeater.DataSource = jobList;
            JobListRepeater.DataBind();
            lblJobsCount.InnerText = itemCount.ToString();
            lblLRTime.InnerText = DateTime.Now.ToFormatString();
        }

        /// <summary>
        /// 列表事件
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void JobListRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            long id = 0;
            long.TryParse(e.CommandArgument.ToString(), out id);

            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                if (e.CommandArgument != null && (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem))
                {
                    JobStatus jobStatus = JobStatus.Pending;
                    switch (e.CommandName.ToString().Trim())
                    {
                        //暂停Job运行
                        case "Pause":
                            jobStatus = JobStatus.Paused;
                            break;
                        //恢复Job运行
                        case "Resume":
                        case "Reset":
                            jobStatus = JobStatus.Pending;
                            break;
                        //删除运行的Job
                        case "Delete":
                            jobStatus = JobStatus.Deleted;
                            break;
                    }
                    bool result = StoreManager.Current.JobStore.SetJobStatuses(id, null, jobStatus);
                    if (!result)
                    {
                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script  type='text/javascript'>alert('Please refresh this list & try again!')</script>");
                    }
                }
            }
            DoBindData(ctPager.CurrentPageIndex);
        }

        protected void JobListRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            JobData info = (JobData)e.Item.DataItem;
            LinkButton lkResume = e.Item.FindControl("lkbResume") as LinkButton;
            LinkButton lkPause = e.Item.FindControl("lkbPause") as LinkButton;
            LinkButton lkReset = e.Item.FindControl("lkbReset") as LinkButton;

            JobStatus nowStatus = info.Status;

            if (info.ScheduleRunningType == "Run Once")
            {
                    lkResume.Style["display"] = "none";
                    lkPause.Style["display"] = "none";
                    lkReset.Style["display"] = "inline";
            }
            else
            {
                //如果当前状态是暂停，则显示恢复按钮，隐藏暂停按钮，如果是恢复状态，则默认（隐藏恢复按钮，显示暂停按钮）
                if (nowStatus == JobStatus.Paused)
                {
                    lkResume.Style["display"] = "inline";
                    lkPause.Style["display"] = "none";
                    lkReset.Style["display"] = "none";
                }
                //如果当前状态是失败状态，则隐藏恢复按钮\暂停按钮
                else if (nowStatus == JobStatus.Fail || nowStatus == JobStatus.ShutdownTimeout)
                {
                    lkResume.Style["display"] = "none";
                    lkPause.Style["display"] = "none";
                    lkReset.Style["display"] = "inline";
                }
                else
                {
                    lkResume.Style["display"] = "none";
                    lkPause.Style["display"] = "inline";
                    lkReset.Style["display"] = "none";
                }
            
            }
            if (nowStatus == JobStatus.Executing)
            {
                Image img = e.Item.FindControl("imgRunning") as Image;
                img.Style["display"] = "inline";

                Label lbl = e.Item.FindControl("lblStatus") as Label;
                lbl.Style["display"] = "none";
            }
        }
    }

}